<template>
	<div class="full-screen-bg">
		<div class="form-container">
			<h2 class="HighTitle">健康档案管理系统</h2>
			<h3 class="LoginText">账号登陆</h3>
			<el-form ref="form" :rules="rules" :model="form" label-width="80px">
				<el-form-item label="账号" prop="username">
					<el-input v-model="form.username" prefix-icon="el-icon-user"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="form.password" type="password" prefix-icon="el-icon-unlock"
						show-password></el-input>
				</el-form-item>

				<el-form-item class="enroll-submit">
					<el-button type="primary" @click="onEnroll">注册</el-button>
					<el-button type="primary" @click="onSubmit" :loading="creating">提交</el-button>
				</el-form-item>
			</el-form>
		</div>
	</div>
</template>

<script>
	import http from '../utils/request';
	import { setToken } from '../utils/auth'; 
	export default {
		data() {
			return {
				creating: false,
				form: {
					username: '',
					password: '',
				},
				rules: {
					username: [{
							required: true,
							message: '请输入账号',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 20,
							message: '长度在 3 到 20 个字符',
							trigger: 'blur'
						}
					],
					password: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}]
				}
			};
		},

		methods: {
			onEnroll() {
				this.$router.push('/enroll');
			},

			async onSubmit() {
				// 先验证表单
				this.$refs.form.validate(async (valid) => {
					if (!valid) {
						this.$message.error('请正确填写表单');
						return;
					}

					console.log('提交的表单数据:', this.form);
					this.creating = true;

					try {
						const result = await this.submit();
						console.log('/login请求成功，返回数据:', result);
						this.handleLoginSuccess(result);
					} catch (error) {
						console.error('提交失败:', error);
						if (error.response && error.response.data) {
							this.$message.error(error.response.data.msg || '登录失败');
						} else {
							this.$message.error('登录失败，请检查网络连接');
						}
					} finally {
						this.creating = false;
					}
				});
			},

			async submit() {
				try {
					// 使用 URLSearchParams 格式
					// const params = new URLSearchParams();
					// params.append('username', this.form.username);
					// params.append('password', this.form.password);

					const params = {
						username: this.form.username,
						password: this.form.password
					}
					
					console.log('发送的登录参数:', params);

					const response = await http.post('/login', params, {
						headers: {
							'Content-Type': 'application/json'
						}
					});

					console.log('响应状态:', response.status);
					console.log('完整响应:', response);

					if (response.data && response.data.code === 1) {
						return response.data.data;
					} else {
						throw new Error(response.data?.msg || '登录失败');
					}
				} catch (error) {
					console.error('登录请求失败:', error);
					// 重新抛出错误，让上层处理
					throw error;
				}
			},

			// 处理登录成功的方法
			handleLoginSuccess(userData) {
				console.log('登录成功，用户数据:', userData);

				if (!userData || !userData.token) {
					this.$message.error('登录响应数据异常');
					return;
				}

				console.log("拿到的token:", userData.token);
				// 1. 先更新 localStorage
					setToken(userData.token);
				
				// 存储完整的用户信息到 localStorage
				localStorage.setItem('userInfo', JSON.stringify({
					userId: userData.userId,
					username: userData.username,
					realName: userData.realName,
					userType: userData.userType,
					img: userData.img || ''
				}));

				// 存储到 Vuex
				this.$store.commit('setLogin', {
					token: userData.token,
					isLogin: '1',
					usertype: userData.userType,
				});

				console.log("设置的token:", this.$store.state.token);

				// 存储用户信息
				this.$store.commit('setUserState', {
					img: userData.img || '',
					lastLoginTime: userData.lastLoginTime || null,
					name: userData.realName || userData.username,
					username: userData.username,
					usertype: userData.userType,
					id: userData.userId
				});


				this.$message.success(`欢迎回来，${userData.realName}！`);

				switch(userData.userType){
					case 'doctor':this.$router.push('/doctor');break;
					case 'patient':this.$router.push('/patient');break;
					case 'admin': this.$router.push('/admin');break;
				}
			},
		}
	}
</script>

<style lang="less" scoped>
	// 定义变量
	@container-width: 27.5rem;
	@container-padding: 30px;
	@shadow-color: rgba(0, 0, 0, 0.1);
	@primary-color: #409EFF;
	@title-color: #24729c;
	@border-radius: 8px;
	@transition-time: 0.3s;

	// 背景样式
	.full-screen-bg {
		background-color: #24729c;
		width: 100%;
		height: 100vh;
		position: relative;
	}

	.form-container {
		width: @container-width;
		background: white;
		border-radius: @border-radius;
		box-shadow: 0 4px 20px @shadow-color;
		padding: @container-padding;
		transition: all @transition-time ease;

		// 使用 Flexbox 居中
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.form-container:hover {
		box-shadow: 0 8px 30px darken(@shadow-color, 50%);
		transform: translate(-50%, -50%) scale(1.02);
	}

	// 标题样式
	.HighTitle {
		line-height: 3.125rem;
		text-align: center;
		font-size: 2rem;
		font-weight: 700;
		color: @title-color;
		letter-spacing: 1px;
		text-transform: uppercase;
		margin: 1.5rem 0;
		border-radius: @border-radius;
	}

	.LoginText {
		line-height: 2rem;
		text-align: center;
		font-size: 1.2rem;
		font-weight: 650;
		color: #000000;
		letter-spacing: 10px;
		font-family: fangsong;
		margin: 1.5rem 0;
		padding: 0.8rem 1.5rem;
		border-radius: @border-radius;
	}

	// 表单项目样式
	.el-form-item {
		margin-bottom: 22px;
	}

	// 按钮容器样式
	.enroll-submit {
		display: flex;
		justify-content: center;
		align-items: center;
		gap: 20px;
		margin-top: 30px;
		margin-right: 5rem;

		.el-form-item__content {
			display: flex;
			justify-content: center;
			width: 100%;
		}
	}
</style>